package com.yida.common.core.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yida.common.core.exception.ServiceException;
import com.yida.common.core.request.PullCompanyDataRequest;
import com.yida.common.core.request.SmsRequest;
import com.yida.common.core.web.domain.AjaxResult;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/***
 * @author lqq
 **/
public class HttpApiUtil {

    private static final Logger log = LoggerFactory.getLogger(HttpApiUtil.class);

    /**
     * 发送公维金POST请求
     *
     * @param url 接口地址
     * @param publicKey 公钥
     * @param privateKey 私钥
     * @param request 请求参数
     * @return /
     */
    public static String sendGwjPostRequest(String url, String publicKey, String privateKey, PullCompanyDataRequest request) {
        // 请求API后返回的数据
        String result = HttpUtil.createRequest(Method.POST, url).charset("utf-8").contentType(ContentType.JSON.getValue()).body(JSONUtil.toJsonStr(request)).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String ciphertext = JSONUtil.toJsonStr(jsonObject.get(AjaxResult.DATA_TAG));
        if ("{}".equals(ciphertext) || StrUtil.isBlank(ciphertext)) {
            throw new ServiceException(JSONUtil.toJsonStr(jsonObject.get(AjaxResult.MSG_TAG)));
        }
        String decryptStr = EncryptUtil.decrypt(publicKey, privateKey, ciphertext);
        jsonObject.remove(AjaxResult.DATA_TAG);
        jsonObject.set(AjaxResult.DATA_TAG, decryptStr);
        // 解密
        return JSONUtil.toJsonStr(jsonObject);
    }

    /**
     * 短信Post请求
     * 
     * @param url 请求路径
     * @param request 请求参数
     * @return
     */
    public static String sendSmsPostRequest(String url, SmsRequest request) {
        String result = HttpUtil.createRequest(Method.POST, url).charset("utf-8").contentType(ContentType.JSON.getValue()).body(JSONUtil.toJsonStr(request)).execute().body();
        JSONObject resultJsonObj = JSONUtil.parseObj(result);
        String resultMsg = resultJsonObj.getStr("msg");
        return StrUtil.isNotBlank(resultMsg) ? resultMsg : JSONUtil.toJsonStr(resultJsonObj.getJSONObject("data"));
    }

}
